<!DOCTYPE html>
<html>
  <head>
    <title>Workbox Google Analytics</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <button id="send-ga-pixel">Send GA pixel (GET)</button>
    <button id="send-ga-beacon">Send GA beacon (POST)</button>
    <button id="send-non-ga-request">Send non-GA request</button>
    <button id="dispatch-sync-event">Simulate sync event</button>
    <button id="clear-spied-requests">Clear requests</button>
    <button id="log-spied-requests">Log requests</button>
    <label>
      <input type="checkbox" id="simulate-offline" />
      Simulate offline
    </label>
    <p><strong>Note:</strong> you need to manually register sw.js</p>

    <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=UA-12345-1"
    ></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() {
        dataLayer.push(arguments);
      }
      gtag('js', new Date());
      gtag('config', 'UA-12345-1', {send_page_view: false});

      const messageSW = (data) => {
        return new Promise((resolve) => {
          var messageChannel = new MessageChannel();
          messageChannel.port1.onmessage = (evt) => resolve(evt.data);
          navigator.serviceWorker.controller.postMessage(data, [
            messageChannel.port2,
          ]);
        });
      };

      document.getElementById('send-ga-pixel').onclick = () => {
        gtag('event', 'pixel', {
          transport_type: 'image',
        });
      };

      document.getElementById('send-ga-beacon').onclick = () => {
        gtag('event', 'beacon', {
          transport_type: 'beacon',
        });
      };

      document.getElementById('send-non-ga-request').onclick = () => {
        fetch('https://httpbin.org/get');
      };

      document.getElementById('dispatch-sync-event').onclick = () => {
        messageSW({action: 'dispatch-sync-event'});
      };

      document.getElementById('simulate-offline').onclick = (evt) => {
        messageSW({
          action: 'simulate-offline',
          value: evt.target.checked,
        });
      };

      document.getElementById('clear-spied-requests').onclick = (evt) => {
        messageSW({action: 'clear-spied-requests'});
      };

      document.getElementById('log-spied-requests').onclick = async (evt) => {
        const requests = await messageSW({action: 'get-spied-requests'});
        console.log(requests);
      };
    </script>
  </body>
</html>
